import useStatAnswerData from '@/store/stat-answer-data'
import {
  QUESTION_TYPE_SINGLE,
  QUESTION_TYPE_MULTI,
  QUESTION_TYPE_SELECT,
  QUESTION_TYPE_TEXT,
  QUESTION_TYPE_TEXTAREA,
  QUESTION_TYPE_MATRIX_RADIO,
} from '@/constants/default'
import { formatTime, serialLetter } from '@/utils/utils'

/*
获取问卷, 核心内容如下:
  {
    title
    questions: [ 这里包括了 "description" 类型的问题
      {
        type
        title
        options:[ {id, text} ]
        subTitles: [ {id, text} ]
      }
    ]
  }
将上面内容格式化成这种形式:
  ['填写时间', '问题1', '问题2', '问题3']
  增加一个 '填写时间'
  其中的多选题拆分出来, 有几个选项就有几个问题, 将问题标题和答案拼接起来
  矩阵单选也是一样, 将主标题和子标题拼接起来
*/
function getQuestionList(survey) {
  const surveyTitle = survey.title
  const questionList = ['填写时间']

  survey.questions.forEach(q => {
    if (
      q.type === QUESTION_TYPE_SINGLE ||
      q.type === QUESTION_TYPE_SELECT ||
      q.type === QUESTION_TYPE_TEXT ||
      q.type === QUESTION_TYPE_TEXTAREA
    ) {
      questionList.push(q.title)
    } else if (q.type === QUESTION_TYPE_MULTI) {
      q.options.forEach(o => {
        questionList.push(q.title + ': ' + o.text)
      })
    } else if (q.type === QUESTION_TYPE_MATRIX_RADIO) {
      q.subTitles.forEach(s => {
        questionList.push(q.title + ': ' + s.text)
      })
    }
  })

  return {
    questionList,
    surveyTitle,
  }
}

/*
原本的数据格式:
answers 结构如下:
  [
    { answers: [ {
      type,
      text,
      options: [{id, text}],
      groups: [{options: [{id, text}]}],
    }]}
  ]

要格式化成以下格式:
[
  ['填写时间', '答案1', '答案2']
  其中多选题有多少项就输出多少项答案, 如果该答案没选, 则为空字符串
  矩阵单选每个子问题的答案都拆分出来.
]
*/
function getAnswerList(answers, survey) {
  const answerList = []
  answers.forEach(oneAnswer => {
    const answerLi = [formatTime(oneAnswer.collect_time)]
    oneAnswer.answer.forEach(a => {
      if (a.type === QUESTION_TYPE_TEXT || a.type === QUESTION_TYPE_TEXTAREA) {
        answerLi.push(a.text)
      } else if (
        a.type === QUESTION_TYPE_SINGLE ||
        a.type === QUESTION_TYPE_SELECT
      ) {
        answerLi.push(a.options[0]?.text || '')
      } else if (a.type === QUESTION_TYPE_MATRIX_RADIO) {

        const options = {}
        survey.questions.some(q => {
          if (q.id === a.id) {
            q.options.forEach((o,i) => {
              options[o.id] = serialLetter(i)
            })
            return true
          }
        })

        a.groups.forEach(g => {
          if (g.options[0]?.text) {
            answerLi.push( options[g.options[0].id] + g.options[0].text)
          } else {
            answerLi.push('')
          }
        })

      } else if (a.type === QUESTION_TYPE_MULTI) {
        survey.questions.some(q => {
          if (q.id == a.id) {
            q.options.forEach(o => {
              if (a.options.some(({ id }) => id == o.id)) {
                answerLi.push(o.text)
              } else {
                answerLi.push('')
              }
            })
            return true
          }
        })
      }
    })
    answerList.push(answerLi)
  })
  console.error(answers);
  return answerList
}

export default async function () {
  const statAnswerData = useStatAnswerData()
  const survey = JSON.parse(JSON.stringify(statAnswerData.survey))
  const answers = JSON.parse(JSON.stringify(statAnswerData.answers))
  const { questionList, surveyTitle } = getQuestionList(survey)
  const answerList = getAnswerList(answers, survey)
  // console.log(questionList);
  // console.log(answerList);
  // console.log(...answerList);
  // console.log([questionList, ...answerList]);
  const jsonArr = [questionList, ...answerList]
  let csv = ''
  jsonArr.forEach(row => {
    row.forEach(item => {
      let text = ''
      for (const ch of item) {
        if (ch === ',') text += '，'
        else if (ch === '\n') text += ' '
        else text += ch
      }
      csv += text + ','
    })
    csv += '\n'
  })

  const a = document.createElement('a')
  const blob = new Blob(['\uFEFF', csv], { type: 'text/csv' })

  a.download = `${surveyTitle}.csv`
  a.href = URL.createObjectURL(blob)
  a.click()
  URL.revokeObjectURL(a.href)

  return
}
